import Group from './group'
import Role from './role'
import { isString } from '../utils/index'

class GroupToRole {
  constructor() {
    // 组
    this.state = [
      // {
      //   id: '', //
      //   gid: '', // 组id
      //   rid: '' // 角色id
      // }
    ]
    this.instance = null
  }

  static getInstance() {
    if (!this.instance) {
      this.instance = new GroupToRole()
    }
    return this.instance
  }

  /**
   * 检查分组是否合法
   * @param {*} gid
   */
  checkGroup(gid) {
    let valid = Group.state.some(v => {
      return v.gid === gid
    })
    return valid
  }
  /**
   * 检查角色是否合法
   * @param {*} rid
   */
  checkRole(rid) {
    let valid = Role.state.some(v => {
      return v.rid === rid
    })
    return valid
  }
  /**
   * 设置
   * @param {*} item
   */
  setState(item) {
    if (!item) {
      return false
    }
    if (isString(item.gid) && isString(item.rid)) {
      let checkGroup = this.checkGroup(item.gid)
      if (!checkGroup) {
        return false
      }
      let checkRole = this.checkRole(item.rid)
      if (!checkRole) {
        return false
      }
      item['id'] = this.state.length
      item['code'] = `${item.gid}_${item.rid}`
      let valid = this.state.some(v => {
        return v.code === item['code']
      })
      if (!valid) {
        this.state.push(item)
        return true
      }
    }
    return false
  }
  /**
   * 获取
   * @param {object} item
   */
  getState(item = { gid: '', rid: '' }) {
    if (item && (item.rid || item.gid)) {
      if (isString(item.gid) && isString(item.rid)) {
        return this.state.filter(v => {
          return v.code === `${item.gid}_${item.rid}`
        })
      } else if (isString(item.gid)) {
        return this.state.filter(v => {
          return v.gid === item.gid
        })
      } else if (isString(item.rid)) {
        return this.state.filter(v => {
          return v.rid === item.rid
        })
      }
    }

    return []
  }
}

let _groupToRole = GroupToRole.getInstance()
export default _groupToRole
